package com.nervenets.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.nervenets.Global;
import com.nervenets.utils.AESUtils;
import com.nervenets.utils.JodaUtils;
import com.nervenets.utils.PropertiesLoader;
import com.nervenets.utils.StringUtils;
import com.nervenets.web.entity.UserToken;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Data
public class TokenParams implements Serializable {
    @ApiModelProperty(value = "用户的token", required = true)
    @NotNull(message = "用户的token不能为空")
    private String token;

    public final long resolveUserId() {
        // TODO 加入缓存机制，解析过一次的不需要再次解析（REDIS）
        if (idNullable() && StringUtils.isEmpty(token)) {
            return 0;
        }
        return resolveToken(token);
    }

    public static long resolveToken(String token) {
        String tokenJson;
        try {
            final PropertiesLoader propertiesLoader = Global.getApplicationProperties();
            tokenJson = AESUtils.decryptData(token, propertiesLoader.getProperty("server.aes.key"), propertiesLoader.getProperty("server.aes.iv"));
            if (null == tokenJson) return -1;
            UserToken userToken = JSONObject.parseObject(tokenJson, UserToken.class);
            return userToken.getUserId();
        } catch (Exception e) {
            return -1;
        }
    }

    /**
     * 判定token是否非法
     *
     * @return true非法，false合法
     */
    public boolean tokenIllegal() {
        try {
            if (idNullable() && StringUtils.isEmpty(token)) {
                return true;
            }
            final PropertiesLoader propertiesLoader = Global.getApplicationProperties();

            String tokenJson = AESUtils.decryptData(token, propertiesLoader.getProperty("server.aes.key"), propertiesLoader.getProperty("server.aes.iv"));
            if (null == tokenJson) return true;
            UserToken token = JSONObject.parseObject(tokenJson, UserToken.class);

            return token.getTime() < JodaUtils.getTimestamp();//token7x24小时过期
        } catch (Exception e) {
            System.out.println(token + ",非法请求");
            return true;
        }
    }

    public static String getTokenStr(UserToken userToken) {
        try {
            final PropertiesLoader propertiesLoader = Global.getApplicationProperties();
            return AESUtils.encryptData(new Gson().toJson(userToken), propertiesLoader.getProperty("server.aes.key"), propertiesLoader.getProperty("server.aes.iv"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    protected boolean idNullable() {
        return false;
    }
}
